package com.amos.cmp_android.ui;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;

import com.amos.cmp_android.R;
import com.amos.cmp_android.constant.URLConstant;
import com.amos.cmp_android.model.AcademyModel;
import com.amos.cmp_android.model.FacultyModel;
import com.amos.cmp_android.model.TeacherModel;
import com.amos.cmp_android.net.STError;
import com.amos.cmp_android.net.STNetTask;
import com.amos.cmp_android.presenter.GetTeacherPresenter;
import com.amos.cmp_android.utils.Model2Str;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.view.DraweeView;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

/**
 * Created by Amos on 2016/4/13.
 */
public class TeacherActivity extends AppCompatActivity implements
        STNetTask.BeforeQueryHook, STNetTask.AfterQueryHook, GetTeacherPresenter.GetTeacherListener,
        SwipeRefreshLayout.OnRefreshListener, BaseRecyclerAdapter.OnItemClickListener{

    private Toolbar toolbar;
    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefresh;
    private GetTeacherPresenter presenter;
    private BaseRecyclerAdapter<TeacherModel> adapter;
    private Spinner academy;
    private Spinner faculty;
    private ImageButton search;
    private EditText searchText;
    private ArrayList<TeacherModel> mList;
    private DraweeView draweeView;
    private List<AcademyModel> academyModelList;
    private List<FacultyModel> facultyModelList;
    private Map<String, List<FacultyModel> > facultyMap;
    private ArrayAdapter<String> academyAdapter;
    private ArrayAdapter<String> facultyAdapter;
    private int selectedAcademy;
    private int selectedFaculty;
    private List<String> facultyStrs=new ArrayList<>();
    private List<String> academyStrs=new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_teacher);

        Fresco.initialize(TeacherActivity.this);

        toolbar = (Toolbar) findViewById(R.id.toolbar_t);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView_t);
        swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefresh_t);
        academy = (Spinner) findViewById(R.id.teacher_academy);
        faculty = (Spinner) findViewById(R.id.teacher_faculty);
        search = (ImageButton) findViewById(R.id.ib_search_teacher);
        searchText = (EditText) findViewById(R.id.et_search_teacher);
        recyclerView.setLayoutManager(new LinearLayoutManager(TeacherActivity.this));
        toolbar.setTitle("教师查询");
        setSupportActionBar(toolbar);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        initData();
        initView();
    }

    private void initView() {
        facultyMap = new Hashtable<>();

        academyModelList = presenter.getAcademy(1, 50);//获取学院列表

        academyAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, academyStrs);
        academy.setAdapter(academyAdapter);
        facultyAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, facultyStrs);
        faculty.setAdapter(facultyAdapter);

        academy.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedAcademy = academyModelList.get(position).getAid();
                facultyModelList = presenter.getFaculty(1, 50, selectedAcademy);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
        faculty.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedFaculty = facultyModelList.get(position).getDid();
                presenter.getTeacher(1, 50, selectedFaculty);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = searchText.getText().toString();
                presenter.getTeacherByName(1, 50, text);
            }
        });
    }

    private void initData() {
        mList = new ArrayList<>();
        swipeRefresh.setColorSchemeResources(R.color.blue, R.color.gray, R.color.green, R.color.red);//设置跑动的颜色值
        swipeRefresh.setOnRefreshListener(this);
        adapter = new BaseRecyclerAdapter<TeacherModel>(this, mList) {
            @Override
            public int getItemLayoutId(int viewType) {
                return R.layout.recycler_item_teacher;
            }
            @Override
            public void bindData(RecyclerViewHolder holder, int position, TeacherModel item) {
                draweeView = (DraweeView) holder.getView(R.id.recycler_item_teacher_img);
                draweeView.setController(Fresco.newDraweeControllerBuilder().
                        setUri(Uri.parse(URLConstant.HOST + item .getTurl())).
                        setAutoPlayAnimations(true).build());
                holder.setText(R.id.recycler_item_teacher_name, item.getTname())
                        .setText(R.id.recycler_item_teacher_sex, item.getTsex())
                        .setText(R.id.recycler_item_teacher_xi, String.valueOf(item.getDid()))
                        .setText(R.id.recycler_item_teacher_intro,item.getTintroduction());
            }
        };
        adapter.setOnItemClickListener(this);
        recyclerView.setAdapter(adapter);
        presenter = new GetTeacherPresenter(this);
        presenter.setBeforeQueryHook(this);
        presenter.setAfterQueryHook(this);
        presenter.setListener(this, mList);
//        presenter.getTeacher(1, 50, 1);
    }

    @Override
    public void afterQueryHook() {
        if (swipeRefresh != null && swipeRefresh.isRefreshing())
            swipeRefresh.setRefreshing(false);
    }

    @Override
    public void beforeQueryHook() {
        if (swipeRefresh != null && !swipeRefresh.isRefreshing())
            swipeRefresh.setRefreshing(true);
    }

    @Override
    public void onSuccess(String info) {
        if(info.equals("teacher") || info.equals("byName")) {
            if (adapter != null)
                adapter.notifyDataSetChanged();
            if (swipeRefresh != null && swipeRefresh.isRefreshing())
                swipeRefresh.setRefreshing(false);
            Toast.makeText(this, "查询成功", Toast.LENGTH_SHORT).show();
        }else if(info.equals("academy")){
            //当学院列表获取成功后，获取所有系别列表并存在facultyMap中
//            for(AcademyModel model : academyModelList){
//                facultyMap.put(model.getAname(), presenter.getFaculty(1, 50, model.getAid()));
//            }
            Model2Str.Academys2Str(academyModelList,academyStrs);
            academyAdapter.notifyDataSetChanged();
            Log.e("Amos", "学院名单查询成功");
        }else if(info.equals("faculty")){
            Model2Str.Facultys2Str(facultyModelList,facultyStrs);
            facultyAdapter.notifyDataSetChanged();
            Log.e("Amos", "系别名单查询成功 ");
        }
    }

    @Override
    public void onFailed(STError error) {
        Toast.makeText(this, "查询失败", Toast.LENGTH_SHORT).show();
        Log.e("Amos", "查询失败");
    }

    @Override
    public void onItemClick(View itemView, int pos) {
        TeacherModel model=mList.get(pos);

        Intent intent = new Intent(TeacherActivity.this, ShowTeacherActivity.class);
        intent.putExtra("picUrl", model.getTurl());
        intent.putExtra("name", model.getTname());
        intent.putExtra("sex", model.getTsex());
        intent.putExtra("xi", model.getDid());
        intent.putExtra("intro", model.getTintroduction());
        startActivity(intent);
    }

    @Override
    public void onRefresh() {
        if (swipeRefresh != null && swipeRefresh.isRefreshing())
            swipeRefresh.setRefreshing(false);
    }

    @Override
    public void onBackPressed() {
        if (swipeRefresh.isRefreshing()){
            swipeRefresh.setRefreshing(false);
        }else {
            super.onBackPressed();
        }
    }
}
